/**
 * LeaferJS Bug 自动修复脚本
 * 在编译后自动修复 miniprogram_npm 中的导出 Bug
 */

const fs = require('fs')
const path = require('path')

/**
 * 查找需要修复的内容
 */
const searchPattern = /Object\.defineProperty\(exports, k, \{ enumerable: true, configurable: true, get: function\(\) \{ return __TEMP__\[k\]; \} \}\);/g

/**
 * 替换内容
 */
const replacement = 'var __TEMP2__ =__TEMP__; Object.defineProperty(exports, k, { enumerable: true, configurable: true, get: function() { return __TEMP2__[k]; } });'

/**
 * 递归查找并修复文件
 * @param {string} dir - 目录路径
 */
function fixDirectory(dir) {
  if (!fs.existsSync(dir)) {
    console.log(`⚠️  目录不存在: ${dir}`)
    return 0
  }

  let count = 0
  const files = fs.readdirSync(dir)

  files.forEach(file => {
    const filePath = path.join(dir, file)
    const stat = fs.statSync(filePath)

    if (stat.isDirectory()) {
      count += fixDirectory(filePath)
    } else if (file.endsWith('.js') && !file.endsWith('.map')) {
      const content = fs.readFileSync(filePath, 'utf8')
      if (searchPattern.test(content)) {
        const newContent = content.replace(searchPattern, replacement)
        fs.writeFileSync(filePath, newContent, 'utf8')
        console.log(`✅ 已修复: ${file}`)
        count++
      }
    }
  })

  return count
}

/**
 * 主函数
 */
function ensureMiniPackageJson() {
  const miniRoot = path.join(__dirname, '../unpackage/dist/dev/mp-weixin')
  const pkgPath = path.join(miniRoot, 'package.json')
  if (!fs.existsSync(miniRoot)) return
  if (!fs.existsSync(pkgPath)) {
    const pkg = {
      name: 'mp-weixin-miniprogram',
      version: '0.0.1',
      private: true,
      description: 'WeChat mini program npm deps (isolated)',
      dependencies: { '@leafer-ui/miniapp': '^1.9.12' }
    }
    fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf8')
    console.log(`🆕 已创建: ${pkgPath}`)
  }
}

function main() {
  console.log('========================================')
  console.log('🔧 LeaferJS Bug 自动修复')
  console.log('========================================\n')

  // 确保编译目录存在 package.json（配合 packNpmManually 使用）
  ensureMiniPackageJson()

  const targetDir = path.join(__dirname, '../unpackage/dist/dev/mp-weixin/miniprogram_npm')

  console.log(`📂 目标目录: ${targetDir}\n`)

  const count = fixDirectory(targetDir)

  console.log('\n========================================')
  if (count > 0) {
    console.log(`🎉 修复完成！共修复 ${count} 个文件`)
  } else {
    console.log('ℹ️  未找到需要修复的内容')
  }
  console.log('========================================\n')
}

main()

